﻿package {
	import flash.display.*;
	import flash.text.*;
	import flash.events.*;
	import flash.external.*;
	import flash.net.*;
	import flash.system.*;
	import fl.controls.*;
	import fl.events.*;
	import fl.transitions.Tween;
 	import fl.transitions.easing.*;
	public class SliderPie extends Sprite {
		private var swfId:String;
		private var btSubmit:Button;
		private var pieData:Array;
		private var pie:Sprite;
		private var tip:TextField;
		private var sliders:Sprite;
		private var stageW:Number;
		private var stageH:Number;
		//pie边距
		private var br:Number = 20;
		//滑动条宽
		private var sliderW:Number = 200;
		//行高
		private var lineH:Number = 30;
		//对象列表
		private var sliderList:Array;
		public function SliderPie() {
			stage.scaleMode = "noScale";
			stage.align = "topLeft";
			stage.addEventListener(Event.RESIZE, resizeHd);
			swfId = ExternalInterface.objectID;
			//------------------------------------------------
			pie = new Sprite();
			addChild(pie);
			//
			sliders = new Sprite();
			addChild(sliders);
			//提交按钮
			btSubmit = new Button();
			btSubmit.label = "Submit";
			btSubmit.addEventListener(MouseEvent.CLICK, clickHandler);
			addChild(btSubmit);
			//
			tip = new TextField();
			tip.autoSize = "left";
			tip.selectable = false;
			tip.background = true;
			tip.border = true;
			tip.borderColor = 0xf5f5f5;
			addChild(tip);
			//
			if (ei()) {
				ExternalInterface.addCallback("setPieData", setPieData);
				ExternalInterface.call("getPieData");
			} else {
				//test data
				var arr:Array = new Array();
				//id,name,color,percent
				arr.push([1,"test1","#058DC7",20]);
				arr.push([2,"test2","#50B432",30]);
				arr.push([3,"test3","#ED561B",50]);
				arr.push([4,"test4","#FF0000",0]);
				setPieData(arr);
			}
		}
		private function clickHandler(e:MouseEvent):void {
			var arr:Array = new Array();
			for (var i:uint = 0; i<pieData.length; i++) {
				arr.push([pieData[i][0], pieData[i][3]]);
			}
			if (ei()) {
				ExternalInterface.call("submitPieData", arr);
			} else {
				o(arr);
			}
		}
		private function setPieData(d:Array):void {
			pieData = d;
			showAll();
		}
		private function resizeHd(e:Event):void {
			layout();
		}
		private function layout():void {
			stageW = stage.stageWidth;
			stageH = stage.stageHeight;
			//
			drawPie();
			sliders.x = stageH;
			//trace(sliders.height);
			sliders.y = (stageH - btSubmit.height - br)/2 - pieData.length*lineH/2;
			btSubmit.move(stageH + br + sliderW/2 - btSubmit.width/2, stageH - btSubmit.height);
		}
		private function showAll():void {
			showSliders();
			//
			layout();
		}
		private function showSliders():void {
			var lineY:Number = br;
			var bx:Number = 8;
			var bw:Number = 15;
			sliderList = new Array();
			for (var i:uint = 0; i<pieData.length; i++) {
				var line:Sprite = new Sprite();
				line.y = lineY;
				//
				var colorbox:Sprite = new Sprite();
				var s:String = pieData[i][2].replace(/#/g, "0x");
				var c:Number = Number(s);
				colorbox.graphics.beginFill(c, 1);
				colorbox.graphics.drawRect(0, 3, bw, bw);
				colorbox.graphics.endFill();
				line.addChild(colorbox);
				//
				var slider:Slider = new Slider();
				slider.liveDragging = true;
				slider.addEventListener(SliderEvent.CHANGE, changeHd);
				slider.addEventListener(SliderEvent.THUMB_RELEASE, thumbReleaseHd);
				slider.maximum = 100;
				slider.minimum = 0;
				slider.snapInterval = 0;
				slider.value = pieData[i][3];
				slider.width = sliderW;
				slider.move(bx + bw, 9);
				line.addChild(slider);
				//
				var checkbox:CheckBox = new CheckBox();
				checkbox.addEventListener(MouseEvent.CLICK, lockHd);
				checkbox.x = sliderW + bx + bx + bw;
				checkbox.label = pieData[i][1] + " (" + pieData[i][3] + "%)";
				checkbox.width = 1000;
				line.addChild(checkbox);
				//
				sliderList.push([slider, checkbox]);
				sliders.addChild(line);
				//
				lineY += lineH;
			}
		}
		private function changeHd(e:SliderEvent):void {
			var slider:Slider = e.target as Slider;
			for (var i:uint = 0; i<sliderList.length; i++) {
				if (slider == sliderList[i][0]) {
					sliderList[i][1].label = pieData[i][1] + " (" + slider.value + "%)";
				}
			}
		}
		private function thumbReleaseHd(e:SliderEvent):void {
			var slider:Slider = e.target as Slider;
			//取得可分配对象个数
			var num:Number = -1;
			for (var i:uint = 0; i<sliderList.length; i++) {
				var checkbox:CheckBox = sliderList[i][1];
				if (!checkbox.selected) {
					num++;
				}
			}
			//o(num);
			//
			var oldPercent:Number;
			for (var j:uint = 0; j<sliderList.length; j++) {
				if (slider == sliderList[j][0]) {
					//取得初始值
					oldPercent = pieData[j][3];
					//是否可以分配
					if (num) {
						sliderList[j][1].label = pieData[j][1] + " (" + slider.value + "%)";
						pieData[j][3] = slider.value;
						//开始分配
						var disPercent:int = oldPercent - slider.value;
						setPercent(disPercent, slider);
					} else {
						slider.value = oldPercent;
					}
				}
			}
		}
		private function setPercent(disPercent:int, slider:Slider):void {
			var setList:Array = new Array();
			for (var i:uint = 0; i<sliderList.length; i++) {
				if (slider != sliderList[i][0]) {
					if (!sliderList[i][1].selected) {
						setList.push([sliderList[i][0], i]);
					}
				}
			}
			//
			var listId:int = 0;
			var total:int = Math.abs(disPercent) + 1;
			if (disPercent < 0) {
				while (disPercent < 0) {
					if (setList[listId][0].value > 0) {
						setList[listId][0].value -= 1;
						disPercent ++;
					}
					listId ++;
					if (listId > setList.length - 1) {
						listId = 0;
						total --;
						if (total < 0) {
							break;
						}
					}
				}
			} else {
				while (disPercent > 0) {
					setList[listId][0].value += 1;
					disPercent --;
					listId ++;
					if (listId > setList.length - 1) {
						listId = 0;
					}
				}
			}
			//
			for (var j:uint = 0; j<setList.length; j++) {
				var k:int = setList[j][1];
				sliderList[k][1].label = pieData[k][1] + " (" + setList[j][0].value + "%)";
				pieData[k][3] = setList[j][0].value;
			}
			//如果剩余
			var recent:int = Math.abs(disPercent);
			//trace(recent);
			if (recent) {
				slider.value -= recent;
				//
				for (var ii:uint = 0; ii<sliderList.length; ii++) {
					if (slider == sliderList[ii][0]) {
						//sliderList[i][1].label = pieData[i][1] + " (" + slider.value + "%)";
						pieData[ii][3] = slider.value;
					}
				}
			}
			//画扇形
			drawPie();
		}
		private function lockHd(e:MouseEvent):void {
			var checkbox:CheckBox = e.target as CheckBox;
			for (var i:uint = 0; i<sliderList.length; i++) {
				if (checkbox == sliderList[i][1]) {
					if (checkbox.selected) {
						sliderList[i][0].enabled = false;
					} else {
						sliderList[i][0].enabled = true;
					}
				}
			}
		}
		private function drawPie():void {
			clearPie();
			pie.x = stageH/2;
			pie.y = stageH/2;
			//半径
			var r:Number = stageH/2 - br;
			//饼图背景
			var pieBg:Sprite = new Sprite();
			pieBg.graphics.beginFill(0xf5f5f5, 0.8);
			pieBg.graphics.drawCircle(0, 0, r);
			pieBg.graphics.endFill();
			pie.addChild(pieBg);
			//初始位置
			var degree:Number = 0;
			//饼图扇形
			for (var i:uint = 0; i<pieData.length; i++) {
				var sector:Sprite = new Sprite();
				sector.buttonMode = true;
				pie.addChild(sector);
				//
				var t:String = pieData[i][1] + " (" + pieData[i][3] + "%)";
				var s:String = pieData[i][2].replace(/#/g, "0x");
				var c:Number = Number(s);
				var a:Number = 1;
				var d:Number = Math.round(3.6*pieData[i][3]);
				var n:Number = degree;
				if (i==pieData.length-1) {
					d = 360 - degree;
				}
				degree += d;
				drawSector(sector, r, c, a, d, n, t);
			}
		}
		private function drawSector(sector:Sprite, r:Number, c:Number, a:Number, d:Number, n:Number, t:String) {
			//
			sector.graphics.beginFill(c, a);
			//边框
			sector.graphics.lineStyle(1, 0xffffff, .5);
			//去边
			sector.graphics.lineTo(r, 0);
			//画弧
			for (var i:Number = 0; i<=d; i++) {
				var bx:Number = r*Math.cos(i*Math.PI/180);
				var by:Number = r*Math.sin(i*Math.PI/180);
				sector.graphics.lineTo(bx, by);
			}
			//回原点
			sector.graphics.lineTo(0, 0);
			sector.graphics.endFill();
			//旋转
			sector.rotation = n;
			sector.name = t + "|" + d;
			sector.addEventListener(MouseEvent.CLICK, clickHd);
			sector.addEventListener(MouseEvent.MOUSE_OVER, overHd);
			sector.addEventListener(MouseEvent.MOUSE_OUT, outHd);
			sector.addEventListener(MouseEvent.MOUSE_MOVE, moveHd);
		}
		private function clickHd(e:MouseEvent):void {
			var sector:Sprite = e.target as Sprite;
			if (sector.x || sector.y) {
				new Tween(sector, "x", None.easeIn, sector.x, 0, 0.2, true);
				new Tween(sector, "y", None.easeIn, sector.y, 0, 0.2, true);
			} else {
				var d:Number = Number(sector.name.split("|")[1])/2 + sector.rotation;
				var r:Number = br/2;
				new Tween(sector, "x", None.easeIn, sector.x, r*Math.cos(d*Math.PI/180), 0.2, true);
				new Tween(sector, "y", None.easeIn, sector.y, r*Math.sin(d*Math.PI/180), 0.2, true);
			}
		}
		private function overHd(e:MouseEvent):void {
			tip.visible = true;
		}
		private function outHd(e:MouseEvent):void {
			tip.visible = false;
		}
		private function moveHd(e:MouseEvent):void {
			var sector:Sprite = e.target as Sprite;
			var s:String = sector.name.split("|")[0];
			//trace(s);
			tip.text = s;
			tip.x = mouseX + 18;
			tip.y = mouseY;
		}
		private function clearPie():void {
			while (pie.numChildren) {
				pie.removeChildAt(0);
			}
		}
		//----------------------------------------
		private function ei():Boolean {
			if (ExternalInterface.available) {
				//if (swfId) {
					return true;
				//} else {
					//return false;
				//}
			}
			return false;
		}
		//--------------------------------------------------------------------
		public function o(str:Object):void {
			var lc:LocalConnection = new LocalConnection();
			lc.addEventListener(StatusEvent.STATUS, function(e:Event):void{});
			var s:String = "("+ Math.round(System.totalMemory/1000)/1000 +"M) "+str.toString();
			trace(s);
			lc.send("_cenfun_lc", "cenfunTrace", s);
		}
	}
}